/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package psn.shan.xml.enhancedvalidator.rules;

import java.util.List;
import java.util.Vector;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.tuple.MutablePair;
import org.jdom2.Document;
import org.jdom2.Element;
import org.springframework.context.annotation.Scope;

/**
 * LinkedDynamicSourceRule  <br />
 * 
 * Links dynamic source to references in current document.
 * Current implementation restricts to single reference and uses the first returned element.  
 * 
 * @author Shan
 * 
 */
@Named("LinkedDynamicSourceRule")
@Scope("prototype")
@Slf4j
public class LinkedDynamicSourceRule extends AbstractLinkedRule {
	static {
		mRuleType = RuleType.LINKED_DYNAMIC_SOURCE;		
	}
	
	@Inject
	private RuleSourceAdaptorIfc<String> mRuleSource;
	
	@Override
	public void setAccessor(String aAccessor) {
		super.setAccessor(aAccessor);
		mRuleSource.setAccessor(aAccessor);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> applyRule(Document aInput) {
		List<Element> lElements = getRuledSubjects(aInput);

		List<String> lMessages = new Vector<String>(); 

		for (Element lMatch : lElements) {
			String lMatchedValue = lMatch.getValue();
			log.debug("Matched element is " + lMatch.getName() + " with value " + lMatchedValue);

			List<List<Element>> lReferences = getReferredElements(lMatch); 
			String lReferredValue = lReferences.get(0).get(0).getValue();
			log.debug("Referred element is " + lReferredValue);
			
			if (!mRuleSource.exists(lReferredValue, MutablePair.of(getAttributes().get(0), lMatchedValue))) {
				setException(getException().replace(VALUE_VARIABLE, lMatchedValue));
				setException(getException().replace(REFERENCE_VARIABLE, lReferredValue));
				lMessages.add(getException());
			}
		}

		return lMessages;
	}

}
